package com.yn.common.config;

import java.util.Optional;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * springboot 默认线程池配置
 *
 * @author YN
 */
public class TaskExecutorConfiguration implements AsyncConfigurer {

  /**
   * 获取当前机器的核数
   */
  public static final int CPU_NUM = Runtime.getRuntime().availableProcessors();

  /**
   * 核心线程池大小,默认为CPU核数
   */
  @Value("${thread.pool.corePoolSize:}")
  private Optional<Integer> corePoolSize;

  /**
   * 最大线程数量，默认CPU核数*2
   */
  @Value("${thread.pool.maxPoolSize:}")
  private Optional<Integer> maxPoolSize;

  /**
   * 最大等待任务数量,默认256
   */
  @Value("${thread.pool.queueCapacity:}")
  private Optional<Integer> queueCapacity;

  /**
   * 线程执行时间，默认60s
   */
  @Value("${thread.pool.awaitTerminationSeconds:}")
  private Optional<Integer> awaitTerminationSeconds;

  @Override
  @Bean
  public Executor getAsyncExecutor() {
    ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
    taskExecutor.setCorePoolSize(corePoolSize.orElse(CPU_NUM));
    taskExecutor.setMaxPoolSize(maxPoolSize.orElse(CPU_NUM * 2));
    taskExecutor.setQueueCapacity(queueCapacity.orElse(256));
    taskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
    taskExecutor.setWaitForTasksToCompleteOnShutdown(true);
    taskExecutor.setAwaitTerminationSeconds(awaitTerminationSeconds.orElse(60));
    taskExecutor.setThreadNamePrefix("Task-Thread-");
    taskExecutor.initialize();
    return taskExecutor;
  }
}
